package com.ttmusic.utils.baidu;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ttmusic.activitys.MainActivity;
import com.ttmusic.core.MusicManager;
import com.ttmusic.dao.AlbumInfoDao;
import com.ttmusic.dao.ArtistInfoDao;
import com.ttmusic.dao.MusicInfoDao;
import com.ttmusic.entity.AbstractMusic;
import com.ttmusic.entity.AlbumInfo;
import com.ttmusic.entity.ArtistInfo;
import com.ttmusic.entity.MusicInfo;
import com.ttmusic.utils.LrcUtil;
import com.ttmusic.utils.MusicUtils;
import com.ttmusic.utils.OnlineLrcUtil;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;


/**
 * 百度音乐API接口工具类
 * @author Administrator
 *
 */
public class BaiduMusicUtil {
	
	public static final String DOWNLOAD_SONG_SAVEPATH = Environment.getExternalStorageDirectory().toString()
    		+ "/TTmusic/DOWNLOAD/";
	
	public static final String BAIDU_MUSIC = "http://tingapi.ting.baidu.com/v1/restserver/ting";
	//public static final String BAIDU_MUSIC_ALBUM ="http://play.baidu.com/data/music/box/album";
    //public static final String BAIDU_MUSIC_SUG = "http://sug.music.baidu.com/info/suggestion";
	public static final String BAIDU_MUSIC_DOWNLOADPATH = "http://ting.baidu.com/data/music/links?songIds=";
    
    /**
     * methods
     */
	//获取搜索建议 可以按歌名、歌手名、专辑名搜索
	public static final String SEARCH_CATALOGSUG = "baidu.ting.search.catalogSug";
	//获取搜索建议 类似于baidu.ting.search.catalogSug
    public static final String SEARCH_MERGE = "baidu.ting.search.merge";
    //获取搜索建议 支持歌曲分页 类似于baidu.ting.search.catalogSug
    public static final String SEARCH_COMMON = "baidu.ting.search.common";
	//获取歌词信息
    public static final String SONG_LRC = "baidu.ting.song.lry ";
    //在线播放
    public static final String SONG_PLAY = "baidu.ting.song.play";
    //获取歌曲详细信息
    public static final String GET_SONGINFO = "baidu.ting.song.getInfos";
    //获取歌手信息
    public static final String GET_ARTISTINFO = "baidu.ting.artist.getinfo";  
    //获取歌手的歌曲列表
    public static final String GET_ARTISTSONGLIST = "baidu.ting.artist.getSongList"; 
    //获取歌手的专辑列表;
    public static final String GET_ARTISTALUBMLIST = "baidu.ting.artist.getAlbumList";
    //获取专辑信息
    public static final String GET_ALBUMINFO = "baidu.ting.album.getAlbumInfo";
    
	
	
	
	
    /**
	 * 获取搜索建议
	 * @param keyword 注意keyword若是中文 一定要转码成utf-8
	 * @param handler
	 */
	public static void querySug(String keyword, Handler handler) {
		HttpParams params = new HttpParams();
		params.add("format", "json");
        params.add("method", SEARCH_CATALOGSUG);
        params.add("from", "android");
        params.add("query", OnlineLrcUtil.Encode(keyword));
        String path = BAIDU_MUSIC + "?" + params.getQueryString();
        startQuery(path, handler);
	}
	
//	/**
//     * 关键字搜索 支持分页
//     * @param keyword
//     * @param page_no 当前页码
//     * @param handler
//     */
//    public static void queryCommon(String keyword, int page_no, Handler handler) {
//    	HttpParams params = new HttpParams();
//		params.add("format", "json");
//        params.add("method", SEARCH_COMMON);
//        params.add("from", "android");
//        params.add("query", keyword);
//        params.add("page_no", page_no);
//        params.add("page_size", 30);
//        String path = BAIDU_MUSIC + "?" + params.getQueryString();
//        startQuery(path, handler);
//    }
	
	/**
	 * 获取歌曲详细信息
	 * @param songid 百度音乐API中通过搜索建议获取的歌曲id
	 * @param handler
	 */
	public static void querySongInfo(long songid, Handler handler) {
		HttpParams params = new HttpParams();
		params.add("format", "json");
        params.add("method", SONG_PLAY);
        params.add("songid", songid);
        String path = BAIDU_MUSIC + "?" + params.getQueryString();
        startQuery(path, handler);
	}
	
	/**
	 * 通过songid查询下载地址和在线播放地址
	 * @param songid
	 * @param handler
	 */
	public static void queryDownloadUrlBySongId(long songid, Handler handler) {
		String path = BAIDU_MUSIC_DOWNLOADPATH + songid;
		startQuery(path, handler);
	}
	
//	public static void beginDownload(long songid, final Handler downloadHandler) {
//		Handler handler = new Handler() {
//			@Override
//			public void handleMessage(Message msg) {
//				JSONObject obj = JSONObject.parseObject(msg.obj.toString());
//				if(obj.getInteger("errorCode") == 22000) {
//					JSONArray array = obj.getJSONObject("data").getJSONArray("songList");
//					SongInfoDownload song = JSON.parseObject(array.get(0).toString(), SongInfoDownload.class);
//					download(song, downloadHandler);
//				}else{
//					//一条数据都没搜索到
//					Message msg2 = new Message();
//					msg2.what = 500;
//					msg2.obj = "下载失败：未找到音乐文件！";
//					downloadHandler.sendMessage(msg2);
//				}
//			}
//		};
//		queryDownloadUrlBySongId(songid, handler);
//    }
	
	public static void download(final SongInfoDownload song, final Handler downloadHandler) {
		final String saveFilePath = DOWNLOAD_SONG_SAVEPATH + song.getArtist() + " - " + song.getTitle() + "." + song.getFormat();
		File f = new File(DOWNLOAD_SONG_SAVEPATH);
		if(!f.exists()) f.mkdirs();
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					URL url = new URL(song.getSongLink());
					HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
					httpConn.connect();
					if(httpConn.getResponseCode() == 200) {
						InputStream in = httpConn.getInputStream();
						OutputStream out = new FileOutputStream(saveFilePath);
						byte[] bs = new byte[1024*1024];
						int i;
						while ((i = in.read(bs)) != -1) {
							out.write(bs, 0, i);
						}
						out.flush();
						out.close();
						
						
						//更新一下歌手的图片
						ArtistInfoDao artistDao = ArtistInfoDao.getInstance();
						ArtistInfo artistInfo = artistDao.loadByName(song.getArtist());
						long artistId;
						String artistImgSavePath = MusicUtils.ARTIST_ALBUM_IMAGE_PATH + new Random().nextInt(10000) + System.currentTimeMillis()  + ".png";;
						//将图片下载到本地
						downloadImg(song.getSongPicRadio(), artistImgSavePath);
						if(artistInfo == null) {
							artistInfo = new ArtistInfo(song.getArtist(), 1, artistImgSavePath);
							artistId = artistDao.save(artistInfo);
						}else{
							artistInfo.setNumSongs(artistInfo.getNumSongs() + 1);
							if(null == artistInfo.getAlbumArt() || "".equals(artistInfo.getAlbumArt())) {
								artistInfo.setAlbumArt(artistImgSavePath);
							}
							artistDao.update(artistInfo);
							artistId = artistInfo.getArtistId();
						}
						AlbumInfoDao albumDao = AlbumInfoDao.getInstance();
						AlbumInfo albumInfo = albumDao.loadByName(song.getAlbumName());
						long albumId;
						if(albumInfo == null) {
							albumInfo = new AlbumInfo(song.getAlbumName(), song.getArtist(), 1, artistImgSavePath);
							albumId = albumDao.save(albumInfo);
						}else {
							albumInfo.setNumSongs(albumInfo.getNumSongs() + 1);
							if(null == albumInfo.getAlbumArt() || "".equals(albumInfo.getAlbumArt())) {
								albumInfo.setAlbumArt(artistImgSavePath);
							}
							albumDao.update(albumInfo);
							albumId = albumInfo.getAlbumId();
						}
						
						MusicInfo mi = new MusicInfo(-1L, albumId, artistId, song.getTitle(), song.getAlbumName(), song.getArtist(), song.getDuration(), saveFilePath, new Date().getTime(), 0);
						MusicInfoDao musicDao = MusicInfoDao.getInstance();
						musicDao.save(mi);
						//下载歌词文件
						downloadLrc(song);
						downloadHandler.sendEmptyMessage(200);
					}
					httpConn.disconnect();
				} catch (MalformedURLException e) {
					e.printStackTrace();
					downloadHandler.sendEmptyMessage(500);
				} catch (IOException e) {
					e.printStackTrace();
					downloadHandler.sendEmptyMessage(500);
				}
			}
		}).start();
	}
	
	/**
	 * 将歌手图片下载到本机
	 * @param url
	 * @param savePath
	 */
	private static void downloadImg(final String url, final String savePath) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				File f = new File(MusicUtils.ARTIST_ALBUM_IMAGE_PATH);
				if(!f.exists()) f.mkdirs();
				HttpURLConnection httpConn;
				try {
					httpConn = (HttpURLConnection)new URL(url).openConnection();
					httpConn.connect();
					if(httpConn.getResponseCode() == 200) {
						InputStream in = httpConn.getInputStream();
						OutputStream out = new FileOutputStream(savePath);
						byte[] bs = new byte[1024*1024];
						int i;
						while((i = in.read(bs)) != -1) {
							out.write(bs, 0, i);
						}
						out.flush();
						out.close();
					}
					httpConn.disconnect();
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	/**
	 * 下载歌词文件
	 * @param song
	 */
	private static void downloadLrc(final SongInfoDownload song) {
		final String lrcFileSavePath = LrcUtil.getLrcPath(song.getArtistName(), song.getSongName());
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					if(null != song.getLrcLink() && !"".equals(song.getLrcLink())) {
						URL url = new URL(song.getLrcLink());
						InputStream in = url.openStream();
						OutputStream out = new FileOutputStream(lrcFileSavePath);
						byte[] bs = new byte[1024];
						int i;
						while((i = in.read(bs)) != -1) {
							out.write(bs, 0, i);
						}
						out.flush();
						out.close();
					}
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	/**
	 * 获取歌手详细信息
	 * @param tinguid
	 * @param handler
	 */
	public static void queryArtistInfo(long tinguid, Handler handler) {
		HttpParams params = new HttpParams();
		params.add("format", "json");
        params.add("method", GET_ARTISTINFO);
        params.add("tinguid", tinguid);
        String path = BAIDU_MUSIC + "?" + params.getQueryString();
        startQuery(path, handler);
	}
	/**
	 * 分页查询歌手的歌曲列表
	 * @param tinguid	歌手的tinguid
	 * @param pageNo	当前页码 从1开始
	 * @param pageSize	每一页展示多少首歌
	 * @param handler
	 */
	public static void queryArtistSongList(long tinguid, int pageNo, int pageSize, Handler handler) {
		HttpParams params = new HttpParams();
		params.add("format", "json");
        params.add("method", GET_ARTISTSONGLIST);
        params.add("tinguid", tinguid);
        params.add("offset", (pageNo-1) * pageSize);
        params.add("limits", pageSize);
        String path = BAIDU_MUSIC + "?" + params.getQueryString();
        startQuery(path, handler);
	}
	
	/**
	 * 开始在线搜索
	 * @param path
	 * @param handler
	 */
	private static void startQuery(final String path, final Handler handler) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					URL url = new URL(path);
					HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
					httpConn.connect();
					if(httpConn.getResponseCode() == 200) {
						BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
						StringBuffer sb = new StringBuffer();
						String temp;
						while ((temp = in.readLine()) != null) {
							sb.append(temp);
						}
						Message msg = new Message();
						msg.what = 200;
						msg.obj = sb.toString();
						handler.sendMessage(msg);
					}
					httpConn.disconnect();
				} catch (MalformedURLException e) {
					Message msg = new Message();
					msg.what = 500;
					msg.obj = e.getMessage();
					handler.sendMessage(msg);
				} catch (IOException e) {
					Message msg = new Message();
					msg.what = 500;
					msg.obj = e.getMessage();
					handler.sendMessage(msg);
				}
			}
		}).start();
	}
	
}
